package br.com.sovi.gwt.client.cercaeletronica;

import java.util.ArrayList;
import java.util.List;

import br.com.sovi.gwt.client.PontoUtils;
import br.com.sovi.gwt.client.entity.Ponto;

import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.event.MapClickHandler;
import com.google.gwt.maps.client.event.PolygonMouseOutHandler;
import com.google.gwt.maps.client.event.PolygonMouseOverHandler;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.overlay.Polygon;

public class CercaMapClickHandler implements MapClickHandler {

	private MapWidget map;

	private Polygon polygon;

	public CercaMapClickHandler(MapWidget map) {
		super();
		this.map = map;
		createPolygon(new LatLng[0]);
	}

	private void createPolygon(LatLng[] lls) {
		if (polygon != null) {
			this.map.removeOverlay(polygon);
		}

		polygon = new Polygon(lls);

		polygon.addPolygonMouseOverHandler(new PolygonMouseOverHandler() {
			@Override
			public void onMouseOver(PolygonMouseOverEvent event) {
				polygon.setEditingEnabled(true);
			}
		});

		polygon.addPolygonMouseOutHandler(new PolygonMouseOutHandler() {
			@Override
			public void onMouseOut(PolygonMouseOutEvent event) {
				polygon.setEditingEnabled(false);
			}
		});

		this.map.addOverlay(polygon);

		polygon.setDrawingEnabled();
	}

	public List<Ponto> getPoints() {
		List<Ponto> pontos = new ArrayList<Ponto>();

		if (polygon != null) {
			int vertexCount = polygon.getVertexCount();

			for (int i = 0; i < vertexCount; i++) {
				pontos.add(PontoUtils.toPoint(polygon.getVertex(i)));
			}
		}

		return pontos;
	}

	@Override
	public void onClick(MapClickEvent event) {
	}

	public void setPolygon(LatLng[] lls) {
		createPolygon(lls);
	}

	public void clear() {
		createPolygon(new LatLng[0]);
	}

}
